let WebSocket = require( 'ws' );
let GameMessage =  require("./GameMsg");

console.log(process.argv);
let username = process.argv[2];
let roomId = process.argv[3];

var ws  = new WebSocket(`ws://localhost:8080/channel?username=${username}&roomId=${roomId}`);

ws.onopen = function(){
    console.log("connect success");
		setInterval(sendMessage, 10);
}
ws.onerror = function(e) {
		console.error("链接出错",e.message);
}
ws.onclose = function(e) {
		console.error("链接关闭",e.message);

}
ws.onmessage = function(evt){
  	let message = evt.data
    let msg = GameMessage.msg.Msg.decode(message);
    switch(msg.type) {
        case GameMessage.msg.TYPE.EMOJI:
            console.log(new Date().toLocaleString(), "receive emoji", msg.emoji.content);
            break;
        case GameMessage.msg.TYPE.TEXT:
            console.log(new Date().toLocaleString(), "receive text", msg.text.content);
    }
}

function sendMessage() {
  let content =  `${username}: 哈哈！`;
  let emoji = GameMessage.msg.Emoji.create({content:content});
	let msg = GameMessage.msg.Msg.create({type:GameMessage.msg.TYPE.EMOJI, emoji:emoji});
  ws.send(GameMessage.msg.Msg.encode(msg).finish());
}
